#!/bin/bash

FROM_REGION=$1
TO_REGION=$2
if [ "$2" == "" ]; then
  TO_REGION=$TF_VAR_REGION
fi
if [[ "$1" == "" || "$TO_REGION" == "" ]]; then
	echo "Usage: $0 <region_name> <to_region_name>"
	echo "Replace <region_name> to <to_region_name> in all tf files."
	echo "Use it in your cation."
	exit 0;
fi

function do_replace(){
FROM=$1
TO=$2
DRY_RUN=$3
if [ "$DRY_RUN" == "true" ]; then
	echo "Dry run: Just finding $FROM in tf files..."
else
	echo "Replacing $FROM to $TO in tf files ..."
fi
for i in `grep -r -l --exclude-dir .terraform  $FROM_REGION *`;do
	if [ "$DRY_RUN" == "true" ]; then
		echo $i
	else
		echo -e -n "$i:\t"
		sed -i ".bak" "s/$FROM/$TO/g" $i
		SEDRT=$?
		if [ $SEDRT -eq 0 ]; then
			echo "OK"
		else
			echo "Failed:$SEDRT"
		fi
	fi
done
}

if [ $FROM_REGION == $TO_REGION ]; then
	echo "You specified same region for from and to: $FROM_REGION."
	echo ""
	do_replace $FROM_REGION $TO_REGION true
else
	do_replace $FROM_REGION $TO_REGION false
fi